import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage'
import { AlertController } from 'ionic-angular';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpProvider {

	SERVER = 'http://127.0.0.1:3000'

  	constructor(public http: Http, public storage: Storage,
		  		public alertCtrl: AlertController) {
    	console.log('Hello HttpProvider Provider');
 	}

 	post(url, params){
 		return new Promise((resolve, reject) => {
 			this.http.post(this.SERVER+url, params)
 			.subscribe(res => {
 				resolve(JSON.parse(res['_body']))
 			}, (err) => {
 				this.show('服务异常')
	            reject(err);
	        })
 		})
 	}

 	get(url){
 		return new Promise((resolve, reject) => {
 			this.http.get(this.SERVER+url)
 			.subscribe(res => {
 				resolve(JSON.parse(res['_body']))
 			}, (err) => {
 				this.show('服务异常')
	            reject(err);
	        })
 		})
 	}

 	authPost(url, params){
 		return new Promise((resolve, reject) => {
 			this.storage.get('token').then((token) => {
	 			let headers = new Headers();
	            headers.append('Content-Type', 'application/json;charset=UTF-8');
	            headers.append('Authorization', 'Bearer '+token);
	            this.http.post(this.SERVER+url, params,{headers: headers})
	 			.subscribe(res => {
	 				resolve(JSON.parse(res['_body']))
	 			}, (err) => {
	 				if(err['status']==401)
	 					this.show('请先登录')
	 				else
	 					this.show('服务异常')
		            reject(err);
		        })
	 		})
 		})
 	}

 	authGet(url){
 		return new Promise((resolve, reject) => {
 			this.storage.get('token').then((token) => {
	 			let headers = new Headers();
	            headers.append('Content-Type', 'application/json;charset=UTF-8');
	            headers.append('Authorization', 'Bearer '+token);
	            this.http.get(this.SERVER+url,{headers: headers})
	 			.subscribe(res => {
	 				resolve(JSON.parse(res['_body']))
	 			}, (err) => {
	 				if(err['status']==401)
	 					this.show('请先登录')
	 				else
	 					this.show('服务异常')
		            reject(err);
		        })
	 		})
 		})
 	}

 	show(text) {
      	let alert = this.alertCtrl.create({
        	subTitle: text,
        	buttons: ['确定']
     	});
      	alert.present(prompt);
  	}

}
